/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { Col, Row, Modal, message, Spin } from 'antd';
import { getList, getRecordList, getRefundInfo } from '@/services/MiniAppManagement';
import OpenModal from '../components/WkdVipMange/OpenModal';
import RecordDetail from '../components/WkdVipMange/RecordDetail';
import { isArray } from 'lodash';

const cardIdMapName: Record<any, string> = {
  1: '月卡',
  2: '季卡',
  3: '年卡',
};

const channelMap: Record<any, string> = {
  aliapp: '支付宝',
  mina: '微信',
};

const WkdVipMange: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [showRecordDetail, setShowRecordDetail] = useState(false);
  const [record, setRecord] = useState<WkdVipMange.ListItem>({} as unknown as WkdVipMange.ListItem);
  const [listId, setListId] = useState('');
  const [channel, setChannel] = useState('');
  const [loading, setLoading] = useState(false);
  const [listTotal, setListTotal] = useState(0);
  const [showType, setShowType] = useState<'list' | 'record' | 'recordDetail'>('list');
  const [searchPhone, setSearchPhone] = useState('');

  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  const onOpenVip = (id: string, userChannel: string) => {
    setVisible(true);
    setListId(id);
    setChannel(userChannel);
  };

  const onCheckInfo = async (id: string, userChannel: string) => {
    setListId(id);
    setLoading(true);
    const {
      code,
      data = [],
      msg,
    } = await getRefundInfo({
      user_id: id,
      page: 1,
      channel: userChannel,
    });
    setLoading(false);
    if (code == 0) {
      let cardInfo: { cardName: string; trade_number: string }[] = [];
      if (isArray(data) && data.length > 0) {
        cardInfo = data.map((val) => ({
          cardName: cardIdMapName[val.card_id],
          trade_number: val.trade_number,
        }));

        Modal.info({
          title: '会员退款',
          okText: '已知晓',
          content: (
            <>
              <div>该用户可操作退款会员为{cardInfo.map((val) => val.cardName).join('、')}</div>
              {cardInfo.map((val) => (
                <div key={val.trade_number}>
                  {val.cardName}（交易流水号）：{val.trade_number}
                </div>
              ))}
            </>
          ),
        });
      } else {
        Modal.info({
          title: '会员退款',
          okText: '已知晓',
          content: '该用户暂无可退款记录',
        });
      }
    } else {
      message.error(msg);
    }
  };

  const columns: ProColumns<WkdVipMange.ListItem>[] = [
    {
      key: 'user_id',
      title: '用户id',
      dataIndex: 'user_id',
      search: false,
      width: '200px',
    },
    {
      key: 'username',
      title: '用户手机号',
      dataIndex: 'username',
      width: '300px',
      fieldProps: {
        placeholder: '请输入正确的手机号',
        allowClear: true,
      },
    },
    {
      key: 'status',
      title: '会员状态',
      dataIndex: 'status',
      search: false,
      width: '250px',
      render: (status) => {
        return status == 0 ? '未开通' : status == '1' ? '开通中' : '已过期';
      },
    },
    {
      key: 'channel',
      title: '平台',
      dataIndex: 'channel',
      search: false,
      width: '250px',
      render: (_, { channel: platform }) => channelMap[platform],
    },
    {
      key: 'expires_time',
      title: '结束时间',
      search: false,
      dataIndex: 'expires_time',
      width: '300px',
    },
    {
      key: 'operate',
      title: '操作',
      width: '350px',
      search: false,
      align: 'center',
      render: (_, records) => {
        const { status, user_id, channel: userChannel } = records;
        return (
          <Row justify='space-around'>
            <Col>
              <a onClick={() => onOpenVip(user_id, userChannel)}>开通会员</a>
            </Col>
            {status == '1' && (
              <Col>
                <Spin spinning={loading && user_id === listId}>
                  <a onClick={() => onCheckInfo(user_id, userChannel)}>退款信息查询</a>
                </Spin>
              </Col>
            )}
            {status != '0' && (
              <Col>
                <Spin spinning={loading && user_id === listId}>
                  <a
                    onClick={() => {
                      setRecord(records);
                      setShowRecordDetail(true);
                    }}
                  >
                    开通记录
                  </a>
                </Spin>
              </Col>
            )}
          </Row>
        );
      },
    },
  ];

  const recordColumns: ProColumns<WkdVipMange.RecordListItem>[] = [
    {
      key: 'user_id',
      title: '用户id',
      dataIndex: 'user_id',
      search: false,
      width: '200px',
    },
    {
      key: 'username',
      title: '用户手机号',
      dataIndex: 'username',
      width: '300px',
      fieldProps: {
        placeholder: '请输入正确的手机号',
        allowClear: true,
      },
    },
    {
      key: 'card_id',
      title: '开通类型',
      dataIndex: 'card_id',
      search: false,
      width: '250px',
      render: (card_id) => {
        return card_id == 2 ? '季卡' : card_id == 1 ? '月卡' : '年卡';
      },
    },
    {
      key: 'channel',
      title: '平台',
      dataIndex: 'channel',
      search: false,
      width: '250px',
      render: (_, { channel: platform }) => channelMap[platform],
    },
    {
      key: 'create_time',
      title: '开通时间',
      search: false,
      dataIndex: 'create_time',
      width: '300px',
    },
    {
      key: 'operate_time',
      title: '操作时间',
      dataIndex: 'operate_time',
      search: false,
      width: '250px',
    },
    {
      key: 'remarks',
      title: '备注',
      dataIndex: 'remarks',
      search: false,
      width: '250px',
    },
    {
      key: 'adm_name',
      title: '操作账号',
      dataIndex: 'adm_name',
      search: false,
      width: '250px',
    },
  ];

  const handleRequest = async (params: any) => {
    const { current: page = 1, ...rest } = params;
    if (['record', 'recordDetail'].includes(showType)) {
      const reqParams: WkdVipMange.RecordSearchParams = {
        mobile: rest.username,
        type: '1',
        page,
      };

      if (channel) {
        reqParams.user_id = listId;
        reqParams.channel = channel;
        delete reqParams.type;
        delete reqParams.mobile;
      }

      const recordList = await getRecordList(reqParams);
      setListTotal(recordList.total || 0);
      return recordList;
    }
    const listData = await getList({ mobile: rest.username });
    setSearchPhone(rest.username);
    setListTotal(listData.total || 0);
    return listData;
  };

  const onRecordClick = (type: 'list' | 'record' | 'recordDetail') => {
    setShowType(type);
    if (type === 'list') {
      formRef.current?.setFieldsValue({ username: searchPhone });
    }
    if (type === 'record') {
      formRef.current?.resetFields();
    }
    formRef.current?.submit();
    setChannel('');
  };

  return (
    <PageContainer>
      <ProTable<WkdVipMange.ListItem | WkdVipMange.RecordListItem>
        actionRef={actionRef}
        formRef={formRef}
        rowKey={({ user_id, id, channel: platform }) => `${id}${platform}${user_id}`}
        options={false}
        pagination={false}
        manualRequest
        headerTitle={`${
          ['record', 'recordDetail'].includes(showType)
            ? showType === 'record'
              ? '操作开通记录'
              : '开通记录'
            : '会员'
        }数据列表：${listTotal}条`}
        toolBarRender={() => [
          <Row key='record' gutter={[10, 0]} align='middle' justify='space-between'>
            <Col>
              <a
                onClick={() => {
                  onRecordClick(showType === 'list' ? 'record' : 'list');
                }}
              >
                {['record', 'recordDetail'].includes(showType) ? '返回' : '操作开通记录'}
              </a>
            </Col>
          </Row>,
        ]}
        columns={['record', 'recordDetail'].includes(showType) ? recordColumns : columns}
        scroll={{ x: 900 }}
        request={handleRequest}
        onReset={() => {
          setChannel('');
          setListId('');
        }}
      />
      <OpenModal
        channel={channel}
        listId={listId}
        visible={visible}
        onCancel={() => setVisible(false)}
        updateList={actionRef.current?.reload}
      />
      <RecordDetail
        record={record}
        visible={showRecordDetail}
        onCancel={() => setShowRecordDetail(false)}
      />
    </PageContainer>
  );
};

export default WkdVipMange;
